package my.assistant.homecashmanager.inoutitem.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.assistant.homecashmanager.inoutitem.data.DmInoutItem;
import my.assistant.homecashmanager.inoutitem.domain.DmInoutItemDomain;
import my.assistant.homecashmanager.inoutitem.utils.InOutItemUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.assistant.common.exception.ImplementNotFoundException;
import org.assistant.common.utils.ClassUtils;
import org.assistant.common.utils.ExtJSUtils;
import org.assistant.common.web.servlet.mvc.Controller;
import org.assistant.common.web.servlet.mvc.Page;
import org.assistant.common.web.servlet.mvc.ResultData;
import org.assistant.csp.data.Global;
import org.assistant.csp.data.UserSession;
import org.assistant.csp.utils.Tree;
import org.assistant.csp.utils.TreeNode;

public class InoutItemController extends Controller {
	private static final long serialVersionUID = -8125429917129972725L;
	private static final Log log = LogFactory.getLog(InoutItemController.class);
	private static final boolean isDebugEnabled = log.isDebugEnabled();

	private DmInoutItemDomain dmInoutItemDomain;

	public InoutItemController() throws ImplementNotFoundException {
		dmInoutItemDomain = ClassUtils
			.getInterfaceImplement(DmInoutItemDomain.class);
	}

	protected Object requestDispatcher(HttpServletRequest request,
			HttpServletResponse response, String methodName) {
		try {
			if ("getAllItems".equals(methodName)) {
				return getAllItems(request, response);
			} else if ("getParentItems".equals(methodName)) {
				return getParentItems(request, response);
			} else if ("insertItem".equals(methodName)) {
				return insertItem(request, response);
			} else {
				return index(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 显示收支项目首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public Page index(HttpServletRequest request, HttpServletResponse response) {
		return new Page("/my/assistant/homecashmanager/inoutitem/IndexItems");
	}

	/**
	 * 获取所有收支项目
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ResultData<?> getAllItems(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserSession userSession = (UserSession) request
			.getSession().getAttribute(Global.CURRENT_USER);

		List<DmInoutItem> inoutItemList = this.dmInoutItemDomain
			.getDmInoutItemByHome(userSession.getHomeId());

		if (isDebugEnabled) {
			log.debug("inoutItemList.size = " + inoutItemList.size());
		}

		StringBuffer buff = getItemNodes(inoutItemList);

		ResultData<?> resultData = new ResultData<String>(buff.toString());

		return resultData;
	}

	/**
	 * 获取父项目
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ResultData<?> getParentItems(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserSession userSession = (UserSession) request
			.getSession().getAttribute(Global.CURRENT_USER);

		List<DmInoutItem> inoutItemList = this.dmInoutItemDomain
			.getDmInoutItemByHome(userSession.getHomeId());

		// 过滤出父项目
		List<DmInoutItem> parentItemList = new ArrayList<DmInoutItem>();
		for (int i = 0; i < inoutItemList.size(); i++) {
			DmInoutItem item = (DmInoutItem) inoutItemList.get(i);
			if (item.getParentid() == 0) {
				parentItemList.add(item);
			}
		}

		if (isDebugEnabled) {
			log.debug("parentItemList.size = " + parentItemList.size());
		}

		StringBuffer buff = getItemNodes(parentItemList);

		ResultData<?> resultData = new ResultData<String>(buff.toString());

		return resultData;
	}

	/**
	 * 添加一条收支项目
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ResultData<?> insertItem(HttpServletRequest request,
			HttpServletResponse response) {
		String name = request.getParameter("name");
		String explain = request.getParameter("explain");
		String inouttype = request.getParameter("inouttype");
		String parentItemId = request.getParameter("comboParentItem");

		if (isDebugEnabled) {
			log.debug("name = " + name);
			log.debug("explain = " + explain);
			log.debug("inouttype = " + inouttype);
			log.debug("parentItemId = " + parentItemId);
		}

		// TODO the method has problem
		response.setContentType("text/javascript;charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.println(ExtJSUtils.getSubmitResult(true, ""));
		} catch (IOException e) {
			e.printStackTrace();
			out.println(ExtJSUtils.getSubmitResult(false, e.getMessage()));
		} finally {
			out.close();
		}

		return null;
	}

	/**
	 * 将菜单数据生成JavaScript数组的形式
	 * 
	 * @param menuList
	 * @return
	 */
	private StringBuffer getItemNodes(List<DmInoutItem> inoutItemList) {
		StringBuffer buff = new StringBuffer();
		if (inoutItemList == null || inoutItemList.size() == 0) {
			return buff.append("[]");
		}

		buff.append("[");

		Tree<DmInoutItem> tree = InOutItemUtil
			.convertInoutItem2Tree(inoutItemList);

		for (int i = 0; i < tree.parentTreeNodeSize(); i++) {
			TreeNode<DmInoutItem> parentNode = tree.getParentTreeNodeByIndex(i);
			buff.append(getChildItemNode(parentNode, 0));// 添加子结点的数据
		}

		buff.deleteCharAt(buff.length() - 1);// 删除最后的逗号
		buff.append("]");
		return buff;
	}

	/**
	 * 获取父结点下的子结点（及子结点的子结点）数据
	 * 
	 * @param parentNode
	 * @param flag
	 *            ，用于标记当前结点是父结点还是子结点。
	 * @return
	 */
	private StringBuffer getChildItemNode(TreeNode<DmInoutItem> parentNode,
			int flag) {
		StringBuffer buff = new StringBuffer();
		buff.append("{");// 本结点开始

		int childrenSize = parentNode.childrenSize();

		DmInoutItem item = parentNode.getNodeData();
		buff.append("id:").append(item.getId()).append(",");
		buff.append("name:\"").append(item.getName()).append("\",");
		String type = item.getInouttype();
		if ("1".equals(type)) {
			type = "<span style='color:green;'>收入</span>";
		} else if ("0".equals(type)) {
			type = "<span style='color:red;'>支出</span>";
		}
		buff.append("inouttype:\"").append(type).append("\",");
		boolean status = item.isStatus();
		String dqzt = "停用";
		if (status) {
			dqzt = "正常";
		} else {
			dqzt = "停用";
		}
		buff.append("status:\"").append(dqzt).append("\",");
		buff.append("explain:\"").append(item.getExplain()).append("\",");
		String leaf = (childrenSize > 0 ? "false" : "true");
		buff.append("leaf:").append(leaf).append(",");
		// if (flag == 0) {
		// buff.append("cls:\"").append("master-task").append("\",");
		// buff.append("iconCls:\"").append("task-folder").append("\",");
		// } else {
		// buff.append("iconCls:\"").append("task").append("\",");
		// }

		if (childrenSize > 0) {
			buff.append("children:[");
			for (int i = 0; i < childrenSize; i++) {
				TreeNode<DmInoutItem> childNode = parentNode.getChild(i);
				buff.append(getChildItemNode(childNode, 1));// 递归生成子结点数据
			}
			buff.deleteCharAt(buff.length() - 1);// 删除最后的逗号
			buff.append("]");
		} else {
			buff.deleteCharAt(buff.length() - 1);// 删除最后的逗号
		}

		buff.append("}");// 本结点结束
		buff.append(",");

		return buff;
	}
}
